import { NextRequest, NextResponse } from 'next/server'
import { getUser } from '@/lib/authUtils'
import prisma from '@/lib/prisma'
import { PLAN_LIMITS, PlanType } from '@/lib/planConfig'
import { calculateUserStorageUsage } from '@/lib/limitChecker'

// 强制动态渲染，因为需要访问请求头
export const dynamic = 'force-dynamic'

export async function GET(request: NextRequest) {
  try {
    const userId = await getUser(request)
    if (!userId) {
      return NextResponse.json({ error: '未授权访问' }, { status: 401 })
    }
    if (userId instanceof NextResponse) {
      return userId
    }

    const user = await prisma.vms_user.findUnique({
      where: { id: userId },
      select: {
        plan_type: true,
        plan_end_date: true
        // 移除 storage_limit 字段查询
      }
    })

    if (!user) {
      return NextResponse.json({ error: '用户不存在' }, { status: 404 })
    }

    // 检查套餐是否过期
    const now = new Date()
    let currentPlan = user.plan_type || 'free'
    if (user.plan_end_date && now > user.plan_end_date) {
      currentPlan = 'free'
    }

    // 直接从配置文件获取存储限制
    const storageUsed = await calculateUserStorageUsage(userId)
    const storageLimit = PLAN_LIMITS[currentPlan as PlanType]?.storage_limit || 100
    const usagePercentage = storageLimit === -1 ? 0 : Math.round((storageUsed / storageLimit) * 100)

    return NextResponse.json({
      storageUsed,
      storageLimit,
      usagePercentage,
      remainingMB: storageLimit === -1 ? -1 : Math.max(0, storageLimit - storageUsed),
      planType: currentPlan
    })
  } catch (error) {
    console.error('获取存储信息失败:', error)
    return NextResponse.json(
      { error: '获取存储信息失败' },
      { status: 500 }
    )
  }
}